package com.example.controller;

import cn.hutool.core.io.FileUtil;
import com.example.common.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.Response;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/files")
public class FileController {
    // 上传路径
    private  static final String filePath = System.getProperty("user.dir") + "/files";//获取当前用户路径

    // 上传文件
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
            if (!FileUtil.exist(filePath)){
                FileUtil.mkdir(filePath);
            }
                // 获取上传的文件名
            String originalFilename= file.getOriginalFilename();
            String realFilePath= filePath +originalFilename;
             if(FileUtil.exist(realFilePath)){
                 originalFilename=FileUtil.mainName(originalFilename) + "_" +
                         System.currentTimeMillis()+"." + FileUtil.extName(originalFilename);
                 realFilePath=filePath + originalFilename;
             }

            File loaclFile = new File(realFilePath);
            file.transferTo(loaclFile);
            String url = "http://localhost:9090/files/download/" + originalFilename;
            return Result.success(url);
    }
    //下载文件
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        response.setHeader( "Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        String realFilePath= filePath + fileName;
        byte[] bytes = FileUtil.readBytes(realFilePath);
        ServletOutputStream os=  response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }
}
